package nl.hva.three2learn.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import nl.hva.three2learn.dao.ChapterDao;
import nl.hva.three2learn.exception.ResourceNotFoundException;
import nl.hva.three2learn.model.Chapter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = "/chapter")
public final class ChapterController extends BaseController {

	@Autowired
	private ChapterDao chapterDao;
	
	@RequestMapping(value = "/view/{chapterId}")
	public String view(HttpServletRequest request,
					   Model model,
					   @PathVariable("chapterId") long chapterId) {
		
		Chapter chapter = chapterDao.findById(chapterId);
		
		if (chapter == null)
			throw new ResourceNotFoundException();
		
		model.addAttribute("chapter", chapter);
		
		File assignmentDir = new File(
				request.getServletContext().getRealPath("/WEB-INF") // Absolute path to the WEB-INF dir
				+ File.separator
				+ "uploads"
				+ File.separator
				+ chapter.getCourse().getId()
				+ File.separator 
				+ chapter.getId()
			);
		
		model.addAttribute("doAssignmentsExist", assignmentDir.exists());
		
		return "chapter/home";
	}
	
}
